package finanz.kontrolle;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import classes.ArrayGenerico;
import classes.Funcoes;
import classes.Parametros;
import classes.SpinAdapterGenerico;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class CategoriaCadastroActivity extends MenuActivity implements OnClickListener {
	
	private Parametros par = Parametros.getInstance();
	private SpinAdapterGenerico adapterTipo;
	private ArrayGenerico[] tipos;
	private String id;
	private Spinner spnTipo;
	private EditText txtNome;
	private EditText txtDescricao;
	
	public void onCreate( Bundle bundle ) {
		super.onCreate( bundle );
		setContentView( R.layout.categoriacadastro );
		
		Bundle extras = getIntent().getExtras();

		id = extras.getString( "LancamentoCategoriaID" );
		
		this.listarCombos();
		
		spnTipo = ( Spinner ) findViewById( R.id.spTipo);
		txtNome = ( EditText ) findViewById( R.id.txtNomeCategoria );
		txtDescricao = ( EditText ) findViewById( R.id.txtDescricaoCategoria );
		
		Button btnSalvarConta = ( Button ) findViewById( R.id.btnSalvar );
		btnSalvarConta.setOnClickListener( this );
		
		Button btnCancelar = ( Button ) findViewById( R.id.btnCancelar );
		btnCancelar.setOnClickListener( this );
	}
	
	public void onClick( View arg0 ) {
		int mensagem = R.string.msgSalvoSucesso;
		
		switch ( arg0.getId()  ) {
			case R.id.btnSalvar:
					if ( spnTipo.getSelectedItemId() == 0 )
						 mensagem =  R.string.msgSelecioneTipo;
					else if ( txtNome.getText().length() <= 0 )
						 mensagem =  R.string.msgPreenchaNome;
					else
						mensagem = this.salvar();
					
					if ( mensagem != R.string.msgSalvoSucesso ) {
						new AlertDialog.Builder( this )
						.setTitle( "Alerta" )
						.setMessage( mensagem )
						.setNeutralButton( "Ok", null).show();
					}
				break;
			case R.id.btnCancelar:
					this.volta();
				break;
		}
	}
	
	private void volta() {
		Intent i = new Intent( CategoriaCadastroActivity.this, CategoriaActivity.class );
		startActivity( i );
		finish();
	}
	
	protected int salvar( ) {
		int mensagem = R.string.msgSalvoSucesso;
		
		String strUrl = par.getUrl().toString() + getResources().getString( R.string.urlCategoriaSalvar );
		
		HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost( strUrl );

	    try {
			List<NameValuePair> CategoriaValuePairs = new ArrayList<NameValuePair>(8);
			CategoriaValuePairs.add(new BasicNameValuePair("DatabaseID", par.getDatabase()));
			CategoriaValuePairs.add(new BasicNameValuePair("LancamentoCategoriaID", id));
			CategoriaValuePairs.add(new BasicNameValuePair("LancamentoTipoID", tipos[ (int) spnTipo.getSelectedItemId() ].getID()));
			CategoriaValuePairs.add(new BasicNameValuePair("Nome", txtNome.getText().toString()));
			CategoriaValuePairs.add(new BasicNameValuePair("Descricao", txtDescricao.getText().toString()));
			httppost.setEntity(new UrlEncodedFormEntity(CategoriaValuePairs));

	        HttpResponse response = httpclient.execute(httppost);

	        Funcoes f = new Funcoes();
	        StringBuilder retorno = f.inputStreamToString( response.getEntity().getContent() );

	        if ( retorno.toString().equals( "1" ) ) {
				mensagem = R.string.msgSalvoSucesso;
				
				Toast t = Toast.makeText( this, mensagem, Toast.LENGTH_SHORT );
				t.setGravity( Gravity.CENTER, 0, 0 );
				t.show();
				
				this.volta();
	        } else
	        	mensagem = R.string.msgErroSalvar;
	        
	    } catch (IOException e) {
	    	mensagem = R.string.msgErroConectar;
	    }
		
	    return mensagem;
	}

	protected <adapter> void listarCombos(  ) {
		String strUrl = par.getUrl().toString() + getResources().getString( R.string.urlListarLancamentoTipo);
		
		HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost( strUrl );

	    try {
	        List<NameValuePair> CategoriaValuePairs = new ArrayList<NameValuePair>( 2 );
	        CategoriaValuePairs.add( new BasicNameValuePair( "DatabaseID", "" + par.getDatabase() ) );
	        
	        if ( !this.id.equals("0" ) ) 
	        	CategoriaValuePairs.add(new BasicNameValuePair("LancamentoCategoriaID", id));
	        
	        httppost.setEntity( new UrlEncodedFormEntity( CategoriaValuePairs ) );

	        HttpResponse response = httpclient.execute( httppost );

	        Funcoes f = new Funcoes();
	        StringBuilder retorno = f.inputStreamToString( response.getEntity().getContent() );
	        
			try {
				
				spnTipo = ( Spinner ) findViewById( R.id.spTipo );
				txtNome = ( EditText ) findViewById( R.id.txtNomeCategoria );
				txtDescricao = ( EditText ) findViewById( R.id.txtDescricaoCategoria );
				
				JSONObject jo = new JSONObject( retorno.toString() );
				JSONArray arrayTipo = jo.getJSONArray( "lancamentotipo" );
				
				tipos = new ArrayGenerico[ arrayTipo.length() ]; 
				
				for ( int p = 0; p < tipos.length; p++ ) {
					JSONObject tipo = new JSONObject( arrayTipo.getJSONObject( p ).toString() );
					
					tipos[ p ] = new ArrayGenerico();
					tipos[ p ].setID( tipo.getString( "LancamentoTipoID" ) );
					tipos[ p ].setLabel( tipo.getString( "Nome" ) );
				}
				
				adapterTipo = new SpinAdapterGenerico( CategoriaCadastroActivity.this, android.R.layout.simple_spinner_item, tipos);
				
				spnTipo.setAdapter( adapterTipo );
				
				 if ( !this.id.equals("0" ) ) {
					 
					JSONObject dados = new JSONObject( jo.getJSONObject( "dados" ).toString() );
					
					int posCategoria = 0;
					for ( int p = 0; p < tipos.length; p++ ) {
						if ( tipos[ p ].getID().equals(dados.getString( "LancamentoTipoID" )) )
							posCategoria = p;
					}
					
					spnTipo.setSelection( posCategoria );
					txtNome.setText( dados.getString( "Nome" ) );
					txtDescricao.setText( dados.getString( "Descricao" ) );
				 } else {
					if ( arrayTipo.length() == 2 )
						spnTipo.setSelection( 1 );
				 }
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
	    }  catch (IOException e) {
	    	e.printStackTrace();
		}

	}

}